package com.talent.controller;

import com.talent.common.Result;
import com.talent.handler.BaseException;
import com.talent.pojo.dto.MenuDTO;
import com.talent.pojo.entity.Menu;
import com.talent.pojo.vo.MenuTreeVO;
import com.talent.pojo.vo.MenuContentDetailVO;
import com.talent.service.MenuService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 菜单管理控制器
 */
@RestController
@RequestMapping("/api/menus")
@Slf4j
public class MenuController {

    @Autowired
    private MenuService menuService;

    /**
     * 获取菜单树形结构
     */
    @GetMapping("/tree")
    public Result<List<MenuTreeVO>> getMenuTree(@RequestParam(required = false) String name) {
        log.info("获取菜单树形结构，筛选条件：{}", name);
        List<MenuTreeVO> menuTree = menuService.getMenuTree(name);
        return Result.success(menuTree);
    }

    /**
     * 根据ID查询菜单内容详情和顶层父级信息
     * 主要用于服务内容项，获取详细信息和层级关系
     */
    @GetMapping("/{id}")
    public Result<MenuContentDetailVO> getById(@PathVariable Long id) {
        log.info("根据ID查询菜单内容详情和顶层父级信息：{}", id);
        MenuContentDetailVO menuDetail = menuService.getContentDetailById(id);
        return Result.success(menuDetail);
    }

    /**
     * 创建菜单
     */
    @PostMapping
    public Result<Menu> create(@Valid @RequestBody MenuDTO menuDTO) {
        log.info("创建菜单：{}", menuDTO);
        Menu menu = menuService.create(menuDTO);
        return Result.success("创建成功", menu);
    }

    /**
     * 更新菜单
     */
    @PutMapping("/{id}")
    public Result<String> update(@PathVariable Long id, @Valid @RequestBody MenuDTO menuDTO) {
        log.info("更新菜单：id={}, data={}", id, menuDTO);
        menuService.update(id, menuDTO);
        return Result.success("更新成功");
    }

    /**
     * 删除菜单
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteById(@PathVariable Long id) {
        log.info("删除菜单：{}", id);
        menuService.deleteById(id);
        return Result.success("删除成功");
    }


    /**
     * 导入菜单
     */
    @PostMapping("/import")
    public Result<String> importMenus(@RequestParam("file") MultipartFile file) {
        log.info("导入菜单：{}", file.getOriginalFilename());
        menuService.importMenus(file);
        return Result.success("导入成功");
    }


    /**
     * 下载服务菜单导入模板
     */
    @GetMapping("/template")
    public void downloadTemplate(HttpServletResponse response) {
        log.info("下载服务菜单导入模板");
        try {
            Resource resource = new ClassPathResource("static/服务菜单导入模版.xlsx");
            InputStream inputStream = resource.getInputStream();
            
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            String fileName = URLEncoder.encode("服务菜单导入模版.xlsx", StandardCharsets.UTF_8);
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            
            // 将文件流写入响应
            StreamUtils.copy(inputStream, response.getOutputStream());
            inputStream.close();
        } catch (IOException e) {
            log.error("下载服务菜单导入模板失败", e);
            throw new BaseException("模板文件下载失败");
        }
    }
}
